package api

import "C"
import (
	"ChdChat-Gin/model"
	"ChdChat-Gin/service"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

func CreateChatGroup(c *gin.Context) {
	var info model.ChatGroups
	if err := c.BindJSON(&info); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": fmt.Sprintf("Parameter format err, %v", err),
		})
		log.Printf("CreateChatGroup.BindJSON:%v\n", err)
		return
	}
	result, err := service.CreateChatGroup(info)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": fmt.Sprintf("Failed to create chat group, %v", err),
		})
		log.Printf("CreateChatGroup.CreateChatGroup:%v\n", err)
		return
	}
	if result > 0 {
		c.JSON(http.StatusOK, gin.H{
			"msg": "Create chat group successfully",
		})
	}
}

func DissolveChatGroup(c *gin.Context) {
	account := c.Query("account")
	if err := service.DissolveChatGroup(account); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": fmt.Sprintf("Failed to dissolve chat group, %v", err),
		})
		log.Printf("DissolveChatGroup.DissolveChatGroup:%v\n", err)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg": "Dissolve chat group successfully",
	})
}

func UpdateChatGroupInfo(c *gin.Context) {
	var info *model.ChatGroups
	if err := c.BindJSON(&info); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": fmt.Sprintf("Parameter format err, %v", err),
		})
		log.Printf("CreateChatGroup.BindJSON:%v\n", err)
		return
	}
	if err := service.UpdateChatGroupInfo(info); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": fmt.Sprintf("Failed to update chat group info, %v", err),
		})
		log.Printf("UpdateChatGroupInfo.UpdateChatGroupInfo:%v\n", err)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg": "Update chat group info successfully",
	})
}

func AddMembers(c *gin.Context) {
	var list = struct {
		members []string
	}{}
	if err := c.BindJSON(&list); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": fmt.Sprintf("Parameter format err, %v", err),
		})
		log.Printf("AddMembers.BindJSON:%v\n", err)
		return
	}
	if err := service.AddMembers(list.members); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": fmt.Sprintf("Failed to add members, %v", err),
		})
		log.Printf("AddMembers.AddMembers:%v\n", err)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg": "Apply successfully, wait for handle",
	})
}

func DeleteMembers(c *gin.Context) {
	var list = struct {
		members []string
	}{}
	if err := c.BindJSON(&list.members); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": fmt.Sprintf("Parameter format err, %v", err),
		})
		log.Printf("DeleteMembers.BindJSON:%v\n", err)
		return
	}
	if err := service.DeleteMembers(list.members); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": fmt.Sprintf("Failed to delete members, %v", err),
		})
		log.Printf("DeleteMembers.DeleteMembers:%v\n", err)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg": "Delete successfully",
	})
}
